package wechat.service.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import wechat.handler.work.WechatServiceHandler;
import wechat.handler.work.webauth.WebAuthHandler;

/**
 * Servlet implementation class ServiceServlet
 */
@WebServlet("/ServiceServlet")
public class ServiceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger log = LoggerFactory.getLogger(ServiceServlet.class);
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServiceServlet() {
        super();
    }

	/**
	 * 微信授权回调
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("ServiceServlet Get");
		
		String appid = request.getAttribute("appid").toString();
		log.info("ServiceServlet Get appid=" + appid);
		
		response.setCharacterEncoding("UTF-8");
		String code = request.getParameter("code");
		String state = request.getParameter("state");
		
		log.info("ServiceServlet code=" + code + " state=" + state);
		try {

			WebAuthHandler webAuthHandler = new WebAuthHandler();
			String redirectURL = webAuthHandler.getRedirectURL(appid,code, state);

			//request.getRequestDispatcher(redirectURL).forward(request,response); 
			response.sendRedirect(redirectURL);
	
		} catch (Exception e) {
			log.info("ServiceServlet doGet 获取openid失败 ",e);
			e.printStackTrace();
		}
	}

	/**
	 * 其他项目请求微信数据
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("ServiceServlet Post");
		
		String appid = request.getAttribute("appid").toString();
		log.info("ServiceServlet Post appid=" + appid);
		
		InputStream input = request.getInputStream();
		WechatServiceHandler wechatServiceHandler = new WechatServiceHandler();
		String process = wechatServiceHandler.process(input);
		
		PrintWriter printWriter = response.getWriter();
		printWriter.write(process);
		printWriter.flush();
		printWriter.close();
	}

}
